package com.vavr.checkincms.controller;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import com.vavr.checkincms.constant.CheckinConstants;
import com.vavr.checkincms.domain.dto.MeetingConfigDTO;
import com.vavr.checkincms.domain.dto.MeetingParticipantDTO;
import com.vavr.checkincms.service.MeetingInfoService;
import com.vavr.checkincms.service.MeetingParticipantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

/**
 * 会议提醒消息推送Controller
 *
 * @since 2024.11
 */
@Slf4j
@RestController
public class MeetingMsgSendController {
    /**
     * meetingInfoService
     */
    private final MeetingInfoService meetingInfoService;

    /**
     * meetingParticipantService
     */
    private final MeetingParticipantService meetingParticipantService;

    private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public MeetingMsgSendController(MeetingInfoService meetingInfoService,
            MeetingParticipantService meetingParticipantService) {
        this.meetingInfoService = meetingInfoService;
        this.meetingParticipantService = meetingParticipantService;
    }

    /**
     * 提醒短信自动发送扫描
     */
    @Scheduled(cron = "${send-msg.corn}")
    public void sendMsg() {
        log.error("开始定时任务,当前时间{}", LocalDateTime.now());
        // 扫描配置表信息获取所有配置信息
        List<MeetingConfigDTO> meetingConfigDTOS = meetingInfoService.queryMeetingConfigByConfigId(
                CheckinConstants.SEND_TIME);
        if (meetingConfigDTOS == null || meetingConfigDTOS.isEmpty()) {
            log.warn("[{}],当前不存在需要推送的配置信息,", LocalDateTime.now());
            return;
        }
        // 判断是否存在未完成的且到了发送时间的会议配置信息
        Instant nowTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant();
        meetingConfigDTOS = meetingConfigDTOS.stream()
                .filter(config -> !CheckinConstants.SEND_OVER.equals(config.getConfigDesc()) && nowTime.isBefore(
                        LocalDateTime.parse(config.getConfigValue()).atZone(ZoneId.systemDefault()).toInstant()))
                .toList();

        if (meetingConfigDTOS.isEmpty()) {
            log.warn("[{}],当前不存在需要推送的配置信息,", LocalDateTime.now());
            return;
        }
        // 循环配置,根据meetingId获取预与会人员,进行短信发送
        meetingConfigDTOS.forEach(this::doSendMsg);

    }

    private void doSendMsg(MeetingConfigDTO config) {
        // 首先根据meetingId 获取与会人员信息
        List<MeetingParticipantDTO> participantS = meetingParticipantService.getMeetingParticipantById(
                config.getMeetingId());
        if (participantS == null || participantS.isEmpty()) {
            log.warn("当前会议[{}]不存在需要推送的人员,", config.getMeetingId());
            return;
        }
        // 获取短信发送配置
        // 循环对每个成员发送短信
    }
}
